<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 产品接口
 */
class Product extends Api
{
    protected $noNeedLogin = ['getSeriesList', 'getColorList', 'getProductList', 'getProductById', 'getProductSearchCondition', 'getProductBanner'];
    protected $noNeedRight = ['*'];

    /**
     * 获取产品列表
     * @throws \think\exception\DbException
     */
    public function getProductList()
    {
        if ($this->request->isPost()) {
            $specIds = $this->request->post('specIds', '');
            $seriesIds = $this->request->post('seriesIds', '');
            $colorIds = $this->request->post('colorIds', '');
            $keyword = $this->request->post('keyword', '');
            $pageIndex = $this->request->post('pageIndex', 1);
            $pageSize = $this->request->post('pageSize', 10);

            $where = [];
            if ($specIds) {
                $specIdList = explode(',', $specIds);
                $where['jps.id'] = ['in', $specIdList];
            }
            if ($seriesIds) {
                $seriesIdList = explode(',', $seriesIds);
                $where['jp.series_id'] = ['in', $seriesIdList];
            }
            if ($colorIds) {
                $colorIdList = explode(',', $colorIds);
                $where['jp.color_id'] = ['in', $colorIdList];
            }
            if ($keyword) {
                $where['jp.product_name'] = ['like', '%' . $keyword . '%'];
            }
            $list = model('\app\admin\model\jy\Product')->alias('jp')
                ->field('jp.*, js.series_name, jc.color_name')
//                ->join('jy_product_specs jps', 'jp.id = jps.product_id and jps.is_del = 0', 'LEFT')
                ->join('jy_series js', 'jp.series_id = js.id', 'LEFT')
                ->join('jy_color jc', 'jp.color_id = jc.id', 'LEFT')
                ->where($where)
                ->where('jp.is_del = 0 and jp.status != "0"')
                ->order("jp.weigh desc, jp.update_time desc")
                ->group('jp.id')
                ->paginate($pageSize, false, ['page' => $pageIndex]);
            if ($list) {
                foreach ($list as &$item) {
                    $item['cover_images'] = cdnurl($item['cover_images']);
                    $item['effect_images'] = cdnurl($item['effect_images']);
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            $this->success('', $result);
        }
    }

    public function getProductById($productId = NULL)
    {
        if (!$productId) {
            $this->error(__('Parameter %s can not be empty', 'productId'));
        }
        $product = model('\app\admin\model\jy\Product')->where('id', $productId)->find();
        if (!$product) {
            $this->error(__('No Results were found'));
        }
        if ($product['status'] == 0 || $product['is_del'] == 1) {
            $this->error(__('No Results were found'));
        }
        $product['cover_images'] = cdnurl($product['cover_images']);
        $effectImagesList = [];
        if ($product['effect_images']) {
            $imagesStrList = explode(',', $product['effect_images']);
            $item['imageCount'] = sizeof($imagesStrList);
            if ($imagesStrList) {
                foreach ($imagesStrList as &$image) {
                    $effectImagesList[] = cdnurl($image);
                }
            }
        }
        $product['effectImagesList'] = $effectImagesList;
        $product['profile_json'] = json_decode($product['profile_json']);
        // 查询产品规格
        $designList = model('\app\admin\model\jy\ProductDesign')->where(['product_id' => $product['id'], 'is_del' => 0])->select();
        if ($designList) {
            foreach ($designList as &$design) {
                $designImages = explode(',', $design['design_images']);
                $designImageList = [];
                if ($designImages) {
                    foreach ($designImages as &$image) {
                        $designImageList[] = cdnurl($image);
                    }
                }
                $design['designImageList'] = $designImageList;
            }
            $product['designList'] = $designList;
        }
        $this->addProductScan($productId);
        $this->success('', $product);
    }

    /**
     * 查询系列列表
     */
    public function getSeriesList()
    {
        $seriesList = model('\app\admin\model\jy\Series')->field('id,series_name,series_images')->where(['is_del' => 0])->order('weigh desc')->select();
        if ($seriesList) {
            foreach ($seriesList as &$Series) {
                $Series['series_images'] = cdnurl($Series['series_images']);
            }
        }
        $this->success('', $seriesList);
    }

    /**
     * 查询色系列表
     */
    public function getColorList()
    {
        $colorList = model('\app\admin\model\jy\Color')->field('id,color_name')->where(['is_del' => 0])->order('weigh desc')->select();
        $this->success('', $colorList);
    }

    /**
     * 系列及产品列表
     */
    public function getProductSearchCondition()
    {
        $seriesList = model('\app\admin\model\jy\Series')->field("id,series_name")->where(['is_del' => 0, 'status' => 1])->order('weigh desc')->select();
        if ($seriesList) {
            foreach ($seriesList as &$series) {
                $series->append([], true);
                $productList = model('\app\admin\model\jy\Product')->field('id,product_name,cover_images')->where(['is_del' => 0, 'series_id' => $series['id'], 'status' => 1])->order('weigh desc')->select();
                if ($productList) {
                    foreach ($productList as &$product) {
                        $product->append([], true);
                        $product['cover_images'] = cdnurl($product['cover_images']);
                    }
                }
                $series['productList'] = $productList;
            }
        }
        $this->success('', $seriesList);
    }

    public function getProductListBySeriesId($seriesId = NULL)
    {
        if (!$seriesId) {
            $this->error(__('Parameter %s can not be empty', 'seriesId'));
        }
        $productList = model('\app\admin\model\jy\Product')->where(['is_del' => 0, 'series_id' => $seriesId])->order('weigh desc')->select();
        if ($productList) {
            foreach ($productList as &$product) {
                $product['cover_images'] = cdnurl($product['cover_images']);
                $product['effect_images'] = cdnurl($product['effect_images']);
            }
        }
        $this->success('', $productList);
    }

    private function addProductScan($productId = NULL)
    {
        if (!$this->auth->isLogin()) {
            return false;
        }
        $product = model('\app\admin\model\jy\Product')->where('id', $productId)->find();
        if (!$product) {
            $this->error(__('No Results were found'));
        }
        $userId = $this->auth->id;
        $today = date("Y-m-d", time());
        $row = model('\app\admin\model\jy\ProductScan')->where(['product_id' => $product['id'], 'user_id' => $userId, 'create_time' => ['>=', $today]])->find();
        if ($row) {
            $row['update_time'] = date("Y-m-d H:i:s", time());
            $row->isUpdate(true)->save();
            return true;
        }
        Db::startTrans();
        try {
            // 最多为你保存100条
            $datetime = date("Y-m-d H:i:s", time());
            model('\app\admin\model\jy\ProductScan')->insert(['product_id' => $product['id'], 'user_id' => $userId]);
            $product['scan_count'] = $product['scan_count'] + 1;
            $product['scan_user_count'] = $product['scan_user_count'] + 1;
            $product['update_time'] = $datetime;
            $product->isUpdate(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            return false;
        }
        return true;
    }

    public function getProductBanner()
    {
//        $product_banner = Config::get('site.product_banner');
//        if ($product_banner) {
//            foreach ($product_banner as $key => $banner) {
//                $product_banner[$key] = cdnurl($product_banner[$key]);
//            }
//        }
        $indexBanner = model('\app\common\model\Config')->where('name', 'product_banner')->find();
        $bannerList = [];
        if ($indexBanner) {
            $indexBannerVal = $indexBanner['value'];
            $bannerList = explode(',', $indexBannerVal);
            foreach ($bannerList as $key => $banner) {
                $bannerList[$key] = cdnurl($bannerList[$key]);
            }
        }
        $this->success('', $bannerList);
    }
}